package luke4fun.wheresmymoney.fragments;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

import java.util.Calendar;

import luke4fun.wheresmymoney.util.DateUtil;

public class DatePickerFragment extends DialogFragment implements OnDateSetListener {

	private static EditText et;
	private static String KEY_TIME = "timeInMillis";
	
	public static DatePickerFragment newInstance(View v) {
		return newInstance(v, DateUtil.getTodayInMillis());
	}
	
	public static DatePickerFragment newInstance(View v, long timeInMillis) {
		DatePickerFragment datePicker = new DatePickerFragment();
		Bundle bundle = new Bundle();
		bundle.putLong(KEY_TIME, timeInMillis);
		datePicker.setArguments(bundle);
		et = (EditText) v;
		return datePicker;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		long timeInMillis = getArguments().getLong(KEY_TIME);
		
		// Use the current date as the default date in the picker
		Calendar c = Calendar.getInstance();
		if (timeInMillis != 0) {
			c.clear();
			c.setTimeInMillis(timeInMillis);
		}

		// Create a new instance of DatePickerDialog and return it
		DatePickerDialog dp = new DatePickerDialog(
									getActivity(),
									this,
									c.get(Calendar.YEAR),
									c.get(Calendar.MONTH),
									c.get(Calendar.DAY_OF_MONTH));
		return dp;
	}

	@Override
	public void onDateSet(DatePicker picker, int year, int monthOfYear, int dayOfMonth) {
		et.setText((monthOfYear + 1) + "/" + dayOfMonth + "/" + year);
	}

}
